package com.cms.crash.handler

import android.annotation.SuppressLint
import android.content.Context
import android.os.Environment
import android.util.Log
import com.android.baselibrary.app.MainApplication
import com.android.baselibrary.utils.ToastUtils
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.PrintWriter
import java.text.SimpleDateFormat
import java.util.*
import kotlin.system.exitProcess

class CustomCrashHandler private constructor(private val context: Context):Thread.UncaughtExceptionHandler {
    private val  defaultHandler = Thread.getDefaultUncaughtExceptionHandler()
    private val filePath = context.applicationContext.externalCacheDir!!.absolutePath+"/crash/log/"
    companion object{
        const val TAG = "CustomCrashHandler"
        fun init(context: Context){
            Thread.setDefaultUncaughtExceptionHandler(CustomCrashHandler(context))
        }
    }
    override fun uncaughtException(t: Thread, e: Throwable) {
        Log.i(TAG, "uncaughtException: ${e.message} ")
        if (defaultHandler!=null&&!userHandlerException(e)){
            defaultHandler.uncaughtException(t,e)
        }else{
            ToastUtils.show(MainApplication.mainApplication,e.message)
            android.os.Process.killProcess(android.os.Process.myPid())
            exitProcess(1)
        }



    }

    /**
     * 处理异常
     */
    private fun userHandlerException(exception:Throwable):Boolean{
        if (exception==null) return false
        saveExceptionFile(exception)
        sendException(exception)
       return true
    }
    /**
     * 保存异常信息到SD卡
     */
    @SuppressLint("SimpleDateFormat")
    private fun saveExceptionFile(exception: Throwable) {
        val dir = File(filePath)
        if (!dir.exists()) dir.mkdirs()
        val format = SimpleDateFormat("yyyy-MM-dd:HH-mm-ss").format(Date())
        val file = File("$filePath$format-crash-log.text")
        try {
            val printWriter = PrintWriter(BufferedWriter(FileWriter(file)))
            printWriter.write(exception.stackTraceToString())
            printWriter.flush()
            printWriter.close()
        }catch (e:java.lang.Exception){
            e.printStackTrace()
        }
        Log.i(TAG, "uncaughtException:异常保存成功 ${file.exists()}")
        Log.i(TAG, "uncaughtException:异常保存成功- ${file.absolutePath}")
    }
    /**
     *
     * 将异常信息发送至服务器
     */
    private fun sendException(exception: Throwable) {

    }

}